(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var win = $.createWindow(L('win_login'));
	win.add(new $.ui('navbar')(true, false));
	var ui = $.layout('login');
	win.add(ui.view);

	var txtEmail = $.ui('text_field').create(L('hint_email'));
	var txtPassword = $.ui('text_field').create(L('hint_password'), false, true);
	ui.container.add([txtEmail, txtPassword]);
	ui.view.add($.icon_info());

	if ($.is_debug()) {
		txtEmail.value = L('debug_username');
		txtPassword.value = L('debug_password');
	}

	$.touch(ui.label_forgot_password, function() {
		$.win('forgot_password').reset();
		$.win('home').nav.push($.win('forgot_password'));
	});

	$.tap(ui.btn_signin, function() {
		var email = txtEmail.val();
		var password = txtPassword.val();
		if ($.isNull(email) || !$.isValidEmail(email)) {
			$.a(L('err_login_email_invalid'));
			return;
		} else if ($.isNull(password)) {
			$.a(L('err_login_password_invalid'));
			return;
		} else {
			$.repeat(function() {
				ui.view.height = $.mainContentHeight(true);
				ui.view.scrollTo(0, 0);
			}, 5);
			$.mask();
			if ($.is_login_secure()) {
				$.webservice().secureLogin(email, $.userAuthToken(email, password), function(e) {
					$.mask(false);
					var result = JSON.parse(e);
					if (result.Success === false) {
						$.a(result.Error);
					} else {
						$.currentUserID(result.UserID);
						$.currentUserEmailAddress(result.EmailAddress);
						$.currentUserName(result.UserName);
						$.allowReceiveNotification(result.AllowReceiveRetailerNotification);
						$.badgeNotification(result.UnreadNotificationNumber);
						$.badgeShoppingBag(result.CheckoutNotificationNumber);
						$.win('my_desires').hideView();
						$.openTabgroupAndFocusToMyDesires();
					}
				});
			} else {
				$.webservice().login(email, password, function(e) {
					$.mask(false);
					var result = JSON.parse(e);
					if (result.Success === false) {
						$.a(result.Error);
					} else {
						$.currentUserID(result.UserID);
						$.currentUserEmailAddress(result.EmailAddress);
						$.currentUserName(result.UserName);
						$.allowReceiveNotification(result.AllowReceiveRetailerNotification);
						$.badgeNotification(result.UnreadNotificationNumber);
						$.badgeShoppingBag(result.CheckoutNotificationNumber);
						$.win('my_desires').hideView();
						$.openTabgroupAndFocusToMyDesires();
					}
				});
			}
		}
	});
	win.reset = function() {
		!$.is_debug() && $.emptyTextFields([txtEmail, txtPassword]);
	};

	$.on('focus', win, function() {
		$.ui('text_field').init([txtEmail, txtPassword], ui.view, $.mainContentHeight(true));
	});
	module.exports = win;
})();
